package com.app.web;


import com.app.common.entity.Order;
import com.app.common.service.AccountService;
import com.app.common.service.OrderService;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import java.util.Date;
import java.util.concurrent.CountDownLatch;

/**
 * 分布式事务-1.初始实现
 *
 * 存在问题:并发支持特别差
 * Created by HuaWeiBo on 2019/4/18.
 */
@RestController
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AccountService accountService;
    @Autowired
    private OrderService orderService;
    private static final Logger logger = LoggerFactory.getLogger(CommonController.class);
    @RequestMapping("/distributed")
    @ResponseBody
    public String distributedTransaction(@Param("userId") int userId,
                                         @Param("goodsId") int goodsId,
                                         @Param("count") int count) {
        try {
            String centreNo = "test";
            int money = 1;
            accountService.updateMoney(userId, money);
            Order order = new Order();
            order.setOrderNo(centreNo);
            order.setOrderMoney((double) money);
            order.setOrderDate(new Date());
            order.setOrderGoodsName("g");
            order.setUserId(userId);
            // 第二步(订单)：业务系统操作->生成订单
            orderService.addOrder(order);
        } catch (Exception e) {
            logger.info("--------------服务异常--> 修改失败次数.");
        }
        return "完成操作.";
    }
    @RequestMapping("/distributedTest")
    @ResponseBody
    public String distributedTest(@Param("userId") int userId,
                                         @Param("goodsId") int goodsId,
                                         @Param("count") int count) {
        CountDownLatch countDownLatch = new CountDownLatch(count);
        for (int i = 0; i < count; i++) {
            new Thread(()->{
                try {
                    String centreNo = "test";
                    int money = 1;
                    accountService.updateMoney(userId, money);
                    Order order = new Order();
                    order.setOrderNo(centreNo);
                    order.setOrderMoney((double) money);
                    order.setOrderDate(new Date());
                    order.setOrderGoodsName("g");
                    order.setUserId(userId);
                    // 第二步(订单)：业务系统操作->生成订单
                    orderService.addOrder(order);
                } catch (Exception e) {
                    logger.info("--------------服务异常--> 修改失败次数.");
                }
            }).start();
            countDownLatch.countDown();
        }
        return "完成操作.";
    }
}
